<template>
	<div class="alloc-resource">
		<el-card>
			<div slot="header">
				<!-- <span>分配资源</span> -->
        <el-page-header @back="goBack" content="分配资源"></el-page-header>
			</div>
			<el-tree
				ref="menuTree"
				node-key="id"
				:data="menus"
				:props="defaultProps"
				:default-checked-keys="checkedKeys"
				show-checkbox
				default-expand-all
			></el-tree>
			<div style="text-align: center; margin-top: 20px">
				<el-button @click="resetChecked">清空</el-button>
				<el-button type="primary" @click="onSave">保存</el-button>
			</div>
		</el-card>
	</div>
</template>

<script lang="ts">
import Vue from 'vue'
import {
  getResourceNodeList,
  allocateRoleResources,
  getRoleResources
} from '@/services/resource'
import { getResourceCategories } from '@/services/recourse-category'
import { Tree } from 'element-ui'
interface ObjType {
	[key: string]: string | number | ObjType[];
}

export default Vue.extend({
  name: 'AllocResource',
  props: {
    roleId: {
      type: [String, Number],
      required: true
    }
  },
  data () {
    return {
      menus: [],
      defaultProps: {
        children: 'subMenuList',
        label: 'name'
      },
      checkedKeys: []
    }
  },
  created () {
    this.loadMenus()
    this.loadRoleMenus()
  },
  methods: {
    async loadMenus () {
      const [{ ...resource }, category] = await Promise.all([
        getResourceNodeList(),
        getResourceCategories()
      ])
      const menus = category.data.data.map((item: ObjType) => {
        return {
          ...item,
          subMenuList: resource.data.data.filter(
            (obj: ObjType) => obj.categoryId === item.id
          )
        }
      })
      console.log(menus)

      this.menus = menus
    },
    resetChecked () {
      (this.$refs.menuTree as Tree).setCheckedKeys([])
    },
    async onSave () {
      const resourceIdList = (this.$refs.menuTree as Tree).getCheckedKeys()
      await allocateRoleResources({
        roleId: this.roleId,
        resourceIdList
      })
      this.$message.success('操作成功')
      this.$router.back()
    },
    async loadRoleMenus () {
      const { data } = await getRoleResources(this.roleId)
      this.getCheckedKeys(data.data)
    },
    getCheckedKeys (menus: ObjType[]) {
      menus.forEach((menu) => {
        if (menu.resourceList) {
          this.getCheckedKeys(menu.resourceList as ObjType[])
        } else if (menu.selected) {
          this.checkedKeys = [...this.checkedKeys, menu.id] as never[]
        }
      })
    },
    goBack () {
      this.$router.push('/role')
    }
  }
})
</script>

<style lang="scss" scoped></style>
